<template>
    <div>
        home
        <div>
            <el-button @click="handlePuppeteer">启动 Puppeteer</el-button>
            <el-button @click="handleScreenshot">截图</el-button>
            <el-button @click="handleGetWebview">获取webview</el-button>
            <el-button @click="handleCreateWebview">创建webview</el-button>
            <el-button @click="test111">测试</el-button>
            <el-button @click="test222">抓取抖音评论</el-button>
        </div>
        <div class="flex">
          <div class="w-700px">
            <el-table :data="tableData" :height="'calc(100vh - 132px)'" empty-text="暂无数据" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column label="用户信息" width="220">
                <template #default="{row}">
                  <div class="flex cursor-pointer items-center">
                    <img :src="row?.user?.avatar_thumb?.url_list[0]" alt="" class="w-40px h-40px rounded-[50%]">
                    <div class="ml-1 space-y-1">
                      <div class="text-[#000]">{{row?.user?.nickname}}</div>
                      <div class="text-[12px]">抖音号：{{row?.user?.unique_id || row?.user?.short_id}}</div>
                      <div class="text-[12px]">IP属地：：{{row?.ip_label}}</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="aweme_id" label="所属视频信息" width="220">
                <template #default="{row}">
                  <div class="flex flex-col cursor-pointer">
                    <div class="text-[#000] mb-3 text-[12px]">视频ID：{{row?.aweme_id}}</div>
                    <div class="flex items-center mb-2">
                      <div class="text-[#000] text-[12px]">作者：</div>
                      <img :src="row?.user?.avatar_thumb.url_list[0]" alt="" class="w-28px h-28px rounded-[50%]">
                      <div class="ml-2">
                        <div class="text-[#000]">{{row?.user?.nickname}}</div>
                        <div class="text-[12px]">粉丝数：{{formatNumber(row?.user?.follower_count)}}</div>
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="text" label="评论内容" :sortable="true" :sort-method="sortByCreateTime">
                <template #default="{row}">
                  <div class="text-[#000] mb-2">{{row?.text}}</div>
                  <div class="text-[12px]">{{ secondTimestampToDate(row?.create_time) }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{row}">
                  <div class="flex items-center">
                    <el-button type="primary" size="small" @click="giveALike(row.user.sec_uid)">点赞</el-button>
                    <el-button type="primary" size="small" @click="comment(row.user.sec_uid)">评论</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div id="webviewDiv">

          </div>
        </div>
    </div>
</template>

<script setup>
import {random16} from "@/utils/string_util.js";
import {cookies, cookiesJSON} from "@/utils/cookies.js";
import {ref} from "vue";
import * as events from "node:events";

const giveALike = (homePageId) => {
  window.khj.puppeteer.giveALike(JSON.stringify({
    homePageId: homePageId,
    webviewId: "13123000"
  }))
}

const comment = (homePageId) => {
  window.khj.puppeteer.comment(JSON.stringify({
    homePageId: homePageId,
    webviewId: "13123000",
  }))
}

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const sortByCreateTime = (row1, row2) => {
  return row1.create_time - row2.create_time
}

const formatNumber = (num) => {
  if (typeof num === 'string') {
    if (num.includes('万') || num.includes('亿')) {
      return num
    } else {
      num = parseInt(num)
    }
  }
  if (num < 10000) {
    return num;
  } else if (num < 100000000) {
    return (num / 10000).toFixed(1) + '万';
  } else {
    return (num / 100000000).toFixed(1) + '亿';
  }
}

/**
 * 秒级时间戳转date
 * @param {*} timestamp
 * @returns
 */
const secondTimestampToDate = (timestamp) => {
  const date = new Date(timestamp * 1000);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const tableData = ref([])

const getVideoInfo = (videoId) => {
  let video = commentStore.videoList.find(v => v.aweme_info.aweme_id === videoId).aweme_info
  return {
    title: video.desc,
    avatar: video.author.avatar_thumb.url_list[0],
    nickName: video.author.nickname,
    follower_count: video.author.follower_count
  }
}

const handlePuppeteer = async () => {
  try {
    const result = await window.khj.puppeteer.connect()
    if (result.success) {
      console.log('Puppeteer 连接成功')
    } else {
      console.error('连接失败:', result.error)
    }
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const handleScreenshot = async () => {
  try {
    const result = await window.khj.puppeteer.screenshot()
    if (result.success) {
      console.log('截图保存在:', result.data)
    } else {
      console.error('截图失败:', result.error)
    }
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const test111 = async () => {
  let result = await window.khj.puppeteer.test111(JSON.stringify({webviewId: "13123000"}))
  console.log('获取结果：', result)
}

const test222 = async () => {

  let result = await window.khj.puppeteer.test222(JSON.stringify({webviewId: "13123000", cookies: JSON.parse(cookiesJSON)}))
  console.log('获取结果：', result)
}

const handleGetWebview = async () => {
  console.log("获取webview");
    
  const result = await window.khj.puppeteer.getWebview()
  console.log("result:", result)
}

const handleCreateWebview = async () => {
    const webview = document.createElement('webview')
    // let webviewId = random16()
    let webviewId = "13123000"
    webview.setAttribute('id', webviewId)
    // webview.setAttribute('src', 'https://www.douyin.com')
    webview.setAttribute('src', 'https://www.baidu.com')
    webview.setAttribute('allowpopups', "true")
    webview.setAttribute('useragent', "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.215 Safari/537.36")
    webview.setAttribute('style', 'display:inline-flex;width:1100px;height:700px;')
    document.getElementById('webviewDiv').appendChild(webview)
    webview.addEventListener("dom-ready", () => {
      webview.openDevTools()
      webview.executeJavaScript(`localStorage.setItem("webviewId","${webviewId}"  )`)
      console.log("dom-ready加载完成")
    })
    console.log("webview创建成功, id为:", webviewId);
}

window.khj.puppeteer.commentListUpdate((event, data) => {
  console.log('收到评论：', JSON.parse(data))
  tableData.value.push(...JSON.parse(data))
})

window.khj.puppeteer.commentSucceed((event, data) => {
  console.log('评论成功！！：', JSON.parse(data))
})





</script>

<style lang="scss" scoped>

</style>